package com.leo.javase.thread.itcast;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 测试读写锁
 * @author Lian
 */
public class ReadWriteLockTest {

	public static void main(String[] args) {
		final MyQueue queue = new MyQueue();
		
		for(int i=0; i<3; i++){
			//读线程
			new Thread(new Runnable(){
				@Override
				public void run() {
					while(true){
						//取操作
						queue.get();
					}
				}
			}).start();
			//写线程
			new Thread(new Runnable(){
				@Override
				public void run() {
					while(true){
						//存操作
						queue.put(new Random().nextInt(10000));
					}
				}
			}).start();
		}
		
	}

}
/**
 * 自定义Queue
 * @author Lian
 */
class MyQueue{
	private Object data = null;
	//读写锁
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	/**
	 * 读操作
	 */
	public void get(){
		rwl.readLock().lock();
		try{
			System.out.println(Thread.currentThread().getName()+" be ready to read data!");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+" have read data:"+data);
		}catch(Exception e){
			
		}finally{
			rwl.readLock().unlock();
		}
	}
	/**
	 * 写操作
	 * @param val
	 */
	public void put(Object val){
		rwl.writeLock().lock();
		try{
			System.out.println(Thread.currentThread().getName()+" be ready to write data!");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+" have write data:"+data);
			this.data = val;
		}catch(Exception e){
			
		}finally{
			rwl.writeLock().unlock();
		}
	}
}